package com.cn.tool;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class LoginFilter extends HttpServlet implements Filter
{
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
		throws IOException, ServletException 
	{
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		String path = req.getContextPath();
		String indexPath = req.getScheme()+"://"+req.getServerName()+":8080"+path+"/login.jsp";
		if(req.getRequestURI().indexOf("/css/") != -1) {
			chain.doFilter(request, response);
			return;
		}
		if(req.getRequestURI().indexOf("/image/") != -1) {
			chain.doFilter(request, response);
			return;
		}
		if(req.getRequestURI().indexOf("/js/") != -1) {
			chain.doFilter(request, response);
			return;
		}
		if(req.getRequestURI().endsWith("login.jsp") 
				|| req.getRequestURI().endsWith("register.jsp")) {
			chain.doFilter(request, response);
			return;
		}
		Object loginUser = req.getSession().getAttribute("username");
		if(loginUser == null) {
			res.sendRedirect(indexPath);
			return;
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig arg0) throws ServletException 
	{
		
	}

}
